package leetcode.秋招.阿里;

import leetcode.剑指offer.pojo.TreeNode;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/8/2 18:57
 * @description：
 */
public class Main2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            int n = in.nextInt();
            int[] nums = new int[n];
            int index = 0;
            for (int j = 0; j < nums.length; j++) {
                nums[j] = in.nextInt();
            }
            int[] ans = new int[n];
            CBTInserter cbtInserter = new CBTInserter(new TreeNode(nums[0]));
            for (int j = 1; j < nums.length; j++) {
                cbtInserter.insert(nums[j]);
            }
            TreeNode root = cbtInserter.getRoot();
            Queue<TreeNode> queue = new LinkedList<>();
            if (root != null) {
                queue.offer(root);
            }
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int j = 0; j < size; j++) {
                    TreeNode node = queue.poll();
                    if (node == null) continue;
                    ans[index++] = node.val;
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }
            System.out.println(Arrays.toString(ans));
        }
    }
}

class CBTInserter {
    TreeNode root;
    Deque<TreeNode> deque;

    public CBTInserter(TreeNode root) {
        this.root = root;
        deque = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left == null || node.right == null) {
                deque.offerLast(node);
            }
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    public int insert(int v) {
        TreeNode node = deque.peekFirst();
        deque.offerLast(new TreeNode(v));
        if (node.left == null) {
            node.left = deque.peekLast();
        } else {
            node.right = deque.peekLast();
            deque.pollFirst();
        }
        return node.val;
    }

    public TreeNode getRoot() {
        return root;
    }
}